﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Timers;
using LitJson;
using ddz_server.game;

namespace ddz_server
{
    class ServerMessage
    {

        //正在排队匹配的连接
        public static List<SocketConnection> roomConns = new List<SocketConnection>();
        public static List<Room> rooms = new List<Room>();
        
          
        private static object _lock = new object();
        public static int maxOnline = 10;
        public static int online = 0;

        public static Room newRoom()
        {
            lock (_lock)
            {
                Room room = new Room();
                room.index = rooms.Count;
                rooms.Add(room);
                return room;
            }
        }

        public static void init(int n)
        {
            maxOnline = n;
            Timer aTimer = new Timer();
            aTimer.Elapsed += new ElapsedEventHandler(TimeEvent);
            // 设置引发时间的时间间隔 此处设置为5秒
            aTimer.Interval = 5000;
            aTimer.Enabled = true; 
        }

        public static void conn(SocketServer server,SocketConnection conn)
        {
            Console.WriteLine("客户端连接:" + conn.asSocket().RemoteEndPoint.ToString());
            online++;
            if (online >= maxOnline)
            {
                //在线人数已满
                conn.Send(Message.ONLINE_FULL().ToJson());
                return;
            }
            conn.Property = new Player();
            conn.Send(Message.JOIN_GAME().ToJson());
        }

        public static void message(string content, SocketConnection conn, SocketServer server)
        {
            Console.WriteLine("客户端{0}发来消息{1}" , conn.asSocket().RemoteEndPoint.ToString(),content);
            Message message = JsonMapper.ToObject<Message>(content);
            if (message.type == MessageType.CLIENT_START_ROOM)
            {
                Player player = conn.Property as Player;
                player.startRoomTime = DateTime.Now.Ticks / 1000;
                roomConns.Add(conn);
            }
        }

        public static void close(SocketConnection conn, SocketServer server)
        {
            Console.WriteLine("客户端断开:" + conn.asSocket().RemoteEndPoint.ToString());
            roomConns.Remove(conn);
            online--;
            Player player = conn.Property as Player;
            if (player != null && player.room > 0)
            {
                //玩家逃跑处理
                foreach (SocketConnection sc in rooms[player.room].players)
                {
                    if (conn != sc)
                    {
                        sc.Send(Message.JOIN_GAME().ToJson());
                    }
                }
            }
        }

        //排队函数
        private static void TimeEvent(object source, ElapsedEventArgs e)
        {
            long now = DateTime.Now.Ticks / 1000;
            //获取所有排队超过5秒的连接
            List<SocketConnection> list = roomConns.FindAll(conn =>
            {
                Player player = conn.Property as Player;
                return player.startRoomTime > 0 && now - player.startRoomTime >= 3000;
            });
            if (list.Count == 0)
            {
                return;
            }
            SocketConnection[] conns = new SocketConnection[3];
            Room room = newRoom();
            Console.WriteLine("开启房间" + room.index);
            List<Card> cards = newCards();
            room.cards = cards;
            Random random = new Random();
            int qdz = random.Next(0, 3);
            int ai1Dizhu = 0;
            int ai2Dizhu = 1;
            room.ai = 3 - list.Count;
            if (list.Count == 1 && qdz != 0)
            {
                int temp = random.Next(0, 2);
                if (temp == 1)
                {
                    ai1Dizhu = 1;
                }
                temp = random.Next(0, 2);
                if (temp == 1)
                {
                    ai2Dizhu = 1;
                }
            }else if(list.Count == 2 && qdz == 2){
                int temp = random.Next(0, 2);
                if (temp == 1)
                {
                    ai1Dizhu = 1;
                }
            }
            
            for (int i = 0; i < 3; i++)
            {
                
                if (i < list.Count)
                {
                    SocketConnection conn = list[i];
                    Player player = conn.Property as Player;
                    room.players[i] = conn;
                    roomConns.Remove(conn);
                    player.room = room.index;
                    player.startRoomTime = -1;
                    var playerCards = subList<Card>(cards, 17 * i, 17 * (i + 1));
                    playerCards.Sort((c1, c2) =>
                    {
                        return c2.number.CompareTo(c1.number);
                    });
                    conn.Send(Message.START_ROOM(new int[]{room.index, i,list.Count, qdz, ai1Dizhu,ai2Dizhu},playerCards).ToJson());
                }
            }
        }

        public static List<Card> newCards()
        {
            List<Card> cards = new List<Card>(54);
            for (int i = 0; i < 54; i++)
            {
                cards.Add(new Card(i));
            }
            return RandomSortList<Card>(cards);
        }

        public static List<T> RandomSortList<T>(List<T> ListT)
        {
            Random random = new Random();
            List<T> newList = new List<T>();
            foreach (T item in ListT)
            {
                newList.Insert(random.Next(newList.Count + 1), item);
            }
            return newList;
        }

        private static List<T> subList<T>(List<T> list, int fromIndex, int toIndex)
        {
            if (fromIndex < 0)
                throw new IndexOutOfRangeException("fromIndex = " + fromIndex);
            if (toIndex > list.Count)
                throw new IndexOutOfRangeException("toIndex = " + toIndex);
            if (fromIndex > toIndex)
                throw new IndexOutOfRangeException("fromIndex(" + fromIndex +
                                                   ") > toIndex(" + toIndex + ")");
            List<T> newList = new List<T>();
            for (int i = fromIndex; i < toIndex; i++)
            {
                newList.Add(list[i]);
            }
            return newList;
        }
    }
}
